package com.pospi.pospihold.ui.cash_ui;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lany.sp.SPHelper;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.pospi.pospihold.App;
import com.pospi.pospihold.R;
import com.pospi.pospihold.adapter.RefundGoodsDetailAdapter;
import com.pospi.pospihold.dao.OrderDao;
import com.pospi.pospihold.dialog.WaitingDialog;
import com.pospi.pospihold.dto.CashierMsgDto;
import com.pospi.pospihold.dto.GoodsDto;
import com.pospi.pospihold.dto.OrderBeen;
import com.pospi.pospihold.dto.OrderDto;
import com.pospi.pospihold.dto.PayBeen;
import com.pospi.pospihold.http.LoadServer;
import com.pospi.pospihold.http.MaxNO;
import com.pospi.pospihold.http.UploadData;
import com.pospi.pospihold.ui.base.BaseActivity;
import com.pospi.pospihold.ui.pay_ui.UnionConfig;
import com.pospi.pospihold.util.Api;
import com.pospi.pospihold.util.Constant;
import com.pospi.pospihold.util.GetData;
import com.pospi.pospihold.util.OrderNoUtil;
import com.pospi.pospihold.util.PareseJson;
import com.pospi.pospihold.util.SaveOrderInfo;
import com.tsy.sdk.myokhttp.response.RawResponseHandler;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.pospi.pospihold.ui.pay_ui.UnionConfig.MERCHANTCODE;
import static com.pospi.pospihold.ui.pay_ui.UnionConfig.TERMINALCODE;

public class OrderDetailActivity extends BaseActivity {

    @Bind(R.id.refund_detail_btn)
    Button refundDetailBtn;
    @Bind(R.id.maxno)
    TextView maxno;
    @Bind(R.id.data)
    TextView data;
    @Bind(R.id.cashier_name)
    TextView cashierName;
    @Bind(R.id.sale_type)
    TextView saleType;
    @Bind(R.id.sale_state)
    TextView saleState;
    @Bind(R.id.goods_detail)
    ListView goodslv;
    @Bind(R.id.pay_type_way)
    TextView payTypeWay;
    @Bind(R.id.pay_type_money)
    TextView payTypeMoney;
    @Bind(R.id.goods_num)
    TextView goodsNum;
    @Bind(R.id.discount_total)
    TextView discountTotal;
    @Bind(R.id.yy_money)
    TextView yyMoney;
    @Bind(R.id.ss_money)
    TextView ssMoney;
    @Bind(R.id.zl_money)
    TextView zlMoney;

    private OrderBeen orderDto;
    private RefundGoodsDetailAdapter adapter;
    private List<GoodsDto> goodsDtos;
    private PayBeen payBeen;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_order_detail);
        setTitle("订单详情");
        ButterKnife.bind(this);
        orderDto = (OrderBeen) getIntent().getSerializableExtra(RefundActivity.REFUNDS);
        init();

    }

    public void init() {
        maxno.setText(String.valueOf(orderDto.getOrderNo()));
        data.setText(orderDto.getDate());
//        if (orderDto.getOrderType() == Constant.ORDERTYPE_REFUND) {
//            saleType.setText("退货");
//            saleType.setTextColor(getResources().getColor(R.color.red));
//            refundDetailBtn.setBackgroundColor(getResources().getColor(R.color.grey));
//            refundDetailBtn.setClickable(false);
//        } else {
            saleType.setText("销售");
//        }
        goodsDtos = SaveOrderInfo.changeToList(orderDto.getGoodsDetail());
        payBeen = new Gson().fromJson(orderDto.getPayDetail(), PayBeen.class);
        adapter = new RefundGoodsDetailAdapter(goodsDtos, getApplicationContext());
        goodslv.setAdapter(adapter);
        fixListViewHeight(goodslv);
        cashierName.setText(orderDto.getCashierNo());
        payTypeWay.setText(payBeen.getName());
        payTypeMoney.setText(String.valueOf(orderDto.getAmount()));
        int num = 0;
        double discount = 0;
        for (int i = 0; i < goodsDtos.size(); i++) {
            num += goodsDtos.get(i).getNum();
            discount += goodsDtos.get(i).getDiscount();
        }
        goodsNum.setText(String.valueOf(num));
        yyMoney.setText(String.valueOf(orderDto.getAmount()));
        ssMoney.setText(String.valueOf(orderDto.getAmount()));
        zlMoney.setText(String.valueOf(0));
        discountTotal.setText(String.valueOf(discount));
        if (!"1".equals(orderDto.getOrderType())) {
            refundDetailBtn.setVisibility(View.GONE);
        }
    }

    @OnClick(R.id.refund_detail_btn)
    public void onClick() {
        showRefundDialog();

//        if (orderDto.getHasReturnGoods() == Constant.hasReturnGoods_Yes) {
//            showToast("该订单已经退货！");
//        } else {
//            showRefundDialog();
//        }
//        refundDetailBtn.setClickable(false);
    }

    public void showRefundDialog() {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("您确定要退货吗？")
                .setMessage("点击[确定]后，完成退款操作！")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startRefund();
//                        if (orderDto.getPayway().equals(Constant.PAYMENT_WEIXIN_String)) {
////                            Intent intent = new Intent(OrderDetailActivity.this, CaptureActivity.class);
////                            startActivityForResult(intent, Constant.PAYMENT_WEIXIN);
//                            refund("wx");
//                        } else if (orderDto.getPayway().equals(Constant.PAYMENT_ALIPAY_String)) {
////                            Intent intent = new Intent(OrderDetailActivity.this, CaptureActivity.class);
////                            startActivityForResult(intent, Constant.PAYMENT_ALIPAY);
//                            refund("ali");
//                        } else {
//                            if (new OrderDao(getApplicationContext()).updateOrderInfo(orderDto.getMaxNo())) {
//                                showToast("退货成功");
//                                addorderinfo();
//                                finish();
//                            } else {
//                                showToast("退货失败");
//                                refundDetailBtn.setClickable(true);
//                            }
//                        }

                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .create();
        dialog.show();
    }

    private void startRefund() {
        if (payBeen.getName().equals("支付宝") || payBeen.getName().equals("微信")) {
            requestUnion();
        } else if (payBeen.getName().equals("银行卡")) {

        } else {
            addorderinfo();
        }
    }

    private void requestUnion() {
        unionRefund(orderDto.getPayId(), orderDto.getAmount());
    }

    public void addorderinfo() {
        orderDto.setOrderType("3");
        App.getInstance().getDaoSession().getOrderBeenDao().update(orderDto);

        //得到店铺的Id
        SharedPreferences preferences = getSharedPreferences("StoreMessage", Context.MODE_PRIVATE);

        String Shopid = preferences.getString("Id", "");//得到店铺的ID
        preferences = getSharedPreferences("Token", Context.MODE_PRIVATE);
        String value = preferences.getString("value", "");
        String[] names = value.split("\\,");
        String deviceNo = names[2];//收银机号
        String uid = names[1];
        String cashierNumber = App.getCashierMsgDto().getNumber();
        String sid = GetData.getYYMMDDHHMMSSNoSpellingTime() + GetData.getStringRandom(20);//得到一个32位的随机数
        List<GoodsDto> goodsDtos = SaveOrderInfo.changeToList(orderDto.getGoodsDetail());
        for (int i = 0; i < goodsDtos.size(); i++) {
            int num = goodsDtos.get(i).getNum();
            goodsDtos.get(i).setNum(-num);
        }
        String listinfo = SaveOrderInfo.changeGoodDtoToJson(goodsDtos);
        OrderBeen orderBeen = new OrderBeen();
        orderBeen.setSid(sid);
        orderBeen.setOrderNo(OrderNoUtil.getNumber());
        orderBeen.setAmount("-"+orderDto.getAmount());
        orderBeen.setCashierNo(cashierNumber);
        orderBeen.setDate(GetData.getDataTime());
        orderBeen.setDeviceNo(deviceNo);
        orderBeen.setDiscount("0");
        orderBeen.setGoodsDetail(listinfo);
        orderBeen.setPayDetail(orderDto.getPayDetail());
        orderBeen.setShopNo(Shopid);
        orderBeen.setUid(uid);
        orderBeen.setStutas(UploadData.UP_FAILED);
        orderBeen.setSaveDate(GetData.getYYMMDD());
        orderBeen.setPayId("");//退款所需标识
        orderBeen.setOrderType("2");//销售
        orderBeen.setSaveTiem(GetData.getSearchTime());
        App.getInstance().getDaoSession().getOrderBeenDao().insert(orderBeen);
        refundFinsh();
    }

    private void refundFinsh() {
        OrderNoUtil.updateNumber();
        refundDetailBtn.setVisibility(View.GONE);
        new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage("退货成功")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        OrderDetailActivity.this.finish();
                    }
                }).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }

    public void refund(String mode) {
//        String value = getSharedPreferences("Token", MODE_PRIVATE).getString("value", "");
//        String[] names = value.split("\\,");
//        String uid = names[1];
//        RequestParams params = new RequestParams();
//        params.put("pay_mode", mode);
//        String money = String.valueOf(orderDto.getSs_money());
//        if (mode.equals("wx")) {
//            money = String.valueOf((int) (orderDto.getSs_money() * 100));
//        }
//        params.put("resund_fee", money);
//        params.put("total_fee", money);
//        params.put("transaction_id", orderDto.getPayReturn());
//        params.put("uid", uid);
//        LoadServer.getConnect(getApplicationContext(), Api.REFUND, params, new AsyncHttpResponseHandler() {
//            @Override
//            public void onSuccess(int i, Header[] headers, byte[] bytes) {
//                closeDialog();
//                Log.i("refund", new String(bytes));
//                try {
//                    JSONObject object = new JSONObject(new String(bytes));
//                    if (object.getInt("Result") == 1) {
//                        showToast(object.getString("Message"));
//                        new OrderDao(getApplicationContext()).updateOrderInfo(orderDto.getMaxNo());
//                        addorderinfo();
//                        finish();
//                    } else {
//                        showToast(object.getString("Message"));
//                        refundDetailBtn.setClickable(true);
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//
//            @Override
//            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
//                closeDialog();
//                Log.i("refundfailure", new String(bytes));
//                refundDetailBtn.setClickable(true);
//                try {
//                    JSONObject object = new JSONObject(new String(bytes));
//                    showToast(object.getString("Message"));
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//        });
    }

    private Dialog dialog;

    public void showDialog(String msg) {
        if (dialog == null) {
            dialog = WaitingDialog.createLoadingDialog(this, msg);
            dialog.show();
        }
    }

    public void closeDialog() {
        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }
    }

    public void fixListViewHeight(ListView listView) {
        // 如果没有设置数据适配器，则ListView没有子项，返回。
        ListAdapter listAdapter = listView.getAdapter();
        int totalHeight = 0;
        if (listAdapter == null) {
            return;
        }

        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listViewItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listViewItem.measure(0, 0);
            // 计算所有子项的高度和
            totalHeight += listViewItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        // listView.getDividerHeight()获取子项间分隔符的高度
        // params.height设置ListView完全显示需要的高度
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }
    public void unionRefund(String orderId ,String money) {
        showLoading("");
        int amount  = (int) (Double.parseDouble(money)*100);
        JSONObject object = new JSONObject();
        try {
            object.put("merchantCode", SPHelper.getInstance().getString(MERCHANTCODE,""));
            object.put("terminalCode", SPHelper.getInstance().getString(TERMINALCODE,""));
            object.put("originalOrderId", orderId);
            object.put("refundRequestId", GetData.getStringRandom(10)+orderId);
            object.put("transactionAmount", amount);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.i("pay", object.toString());
        App.getInstance().getMyOkHttp().post()
                .url(UnionConfig.URL_REFUND)
                .jsonParams(object.toString())
                .addHeader("Authorization","OPEN-ACCESS-TOKEN AccessToken="+ SPHelper.getInstance().getString(UnionConfig.TOKEN_MSG))
                .enqueue(new RawResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, String response) {
                        Log.i("pay", response);
                        try {
                            JSONObject json = new JSONObject(response);
                            String errCode = json.getString("errCode");
                            String errInfo = json.getString("errInfo");
                            if (errCode.equals("00")) {
                                Message message = Message.obtain();
                                message.what = PAYSUCCESS;
                                handler.sendMessage(message);
                            } else {
                                Message message = Message.obtain();
                                message.what = PAYFAIL;
                                message.obj = errInfo;
                                handler.sendMessage(message);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, String error_msg) {
                        Log.i("pay", error_msg);
                        Message message = Message.obtain();
                        message.what = PAYFAIL;
                        message.obj = error_msg;
                        handler.sendMessage(message);
                    }
                });
    }
    private static final int PAYSUCCESS = 1;
    private static final int PAYFAIL = 0;
    public Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case PAYSUCCESS:
                    closeLoading();
                    addorderinfo();
                    Toast.makeText(OrderDetailActivity.this, "退货成功", Toast.LENGTH_SHORT).show();
                    break;
                case PAYFAIL:
                    closeLoading();
                    Toast.makeText(OrderDetailActivity.this, "退货失败"+(String)msg.obj, Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

}
